package org.jeecg.common.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author guoyh
 * @ClassName IMJsonUtil
 * @Description
 * @since 2020/8/29 13:31
 **/
@Slf4j
public class IMJsonUtil {

    public static String getJson(Object param){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
            String json = objectMapper.writeValueAsString(param);
            return json;
        } catch (JsonProcessingException e) {
            log.error("bean 转 json 失败,{}",param.toString());
        }
        return "{}";
    }

    public static <T> T parse(String json,Class<T> clazz){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS,true);
            return objectMapper.readValue(json,clazz);
        } catch (IOException e) {
            log.error("json 转 bean 失败,{}",json,e);
        }
        return null;
    }
}
